package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.config.FreemakerConfig;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FreemakerServiceImpl implements FreemakerService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Reference
    private GoodsService goodsService;

    @Reference
    private ItemCatService ItemCatService;

    @Override
    public void createPage(Long goodsId) {
        FileWriter fileWriter = null;
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try{
            Template template = configuration.getTemplate("item.ftl");
            Map map = new HashMap();
            TbGoods goods = goodsService.findGoods(goodsId);
            TbGoodsDesc goodsDesc = goodsService.getGoodsDescById(goodsId);
            List<TbItem> itemList = goodsService.selectItemListByGoodsId(goodsId);
            goods.getCategory1Id();
            TbItemCat itemCat1 = ItemCatService.selectByType(goods.getCategory1Id());
            TbItemCat itemCat2 = ItemCatService.selectByType(goods.getCategory2Id());
            TbItemCat itemCat3 = ItemCatService.selectByType(goods.getCategory3Id());
            map.put("name1",itemCat1.getName());
            map.put("name2",itemCat2.getName());
            map.put("name3",itemCat3.getName());
            map.put("goods",goods);
            map.put("goodsDesc",goodsDesc);
            map.put("itemList",itemList);
            fileWriter = new FileWriter("D:\\goods\\" + goodsId + ".html");
            template.process(map,fileWriter);
            fileWriter.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fileWriter != null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
